package edu.hrbu.kwaidu.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import edu.hrbu.kwaidu.annotation.HasPerms;
import edu.hrbu.kwaidu.common.R;
import edu.hrbu.kwaidu.exception.CustomException;
import edu.hrbu.kwaidu.model.entity.SysUser;
import edu.hrbu.kwaidu.model.vo.SysUserQueryVo;
import edu.hrbu.kwaidu.service.SysUserService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Optional;

import static edu.hrbu.kwaidu.constant.SystemConstant.EXCEPTION_PARAM_BLANK;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author xudengyu
 * @since 2023-12-31
 */
@RestController
@RequestMapping("/system/sysUser")
public class SysUserController {

    @Resource
    private SysUserService sysUserService;

    @HasPerms("bnt.sysUser.list")
    @GetMapping("/{page}/{limit}")
    public R pageCondition(@PathVariable("page") Integer page,
                           @PathVariable("limit") Integer limit,
                           SysUserQueryVo sysUserQueryVo) {
        Page<SysUser> pageParam = sysUserService.pageCondition(page, limit, sysUserQueryVo);
        return R.ok(pageParam);
    }

    @PostMapping("/{id}/{status}")
    public R updateStatus(@PathVariable("id") Long id,
                          @PathVariable("status") Integer status) {
        sysUserService.updateStatus(id, status);
        return R.ok();
    }

    @PostMapping("/del/{id}")
    public R del(@PathVariable("id") Long id) {
        Optional.ofNullable(id).orElseThrow(() -> new CustomException(EXCEPTION_PARAM_BLANK));
        sysUserService.del(id);
        return R.ok();
    }

    @PostMapping("/delBatch")
    public R delBatch(@RequestBody ArrayList<Long> ids) {
        if (ids.isEmpty()) {
            throw new CustomException(EXCEPTION_PARAM_BLANK);
        }
        sysUserService.delBatch(ids);
        return R.ok();
    }

    @PostMapping("/addOrEdit")
    public R addOrEdit(@RequestBody SysUser sysUser) {
        Optional.ofNullable(sysUser).orElseThrow(() -> new CustomException(EXCEPTION_PARAM_BLANK));
        sysUserService.addOrEdit(sysUser);
        return R.ok();
    }

    @PostMapping("/getInfoById/{id}")
    public R getInfoById(@PathVariable("id") Long id) {
        SysUser sysRole = sysUserService.getInfoById(id);
        return R.ok(sysRole);
    }

}
